<template>
  <div class="space-y-6">
    <!-- 搜索和操作区域 -->
    <div class="flex justify-between">
      <div class="flex gap-4">
        <a-input-search
          v-model="searchParams.code"
          placeholder="请输入巡检单号"
          style="width: 200px"
          @search="handleSearch"
        />
        <a-select
          v-model="searchParams.status"
          placeholder="巡检状态"
          style="width: 160px"
          @change="handleSearch"
        >
          <a-option :value="undefined">全部状态</a-option>
          <a-option :value="0">待巡检</a-option>
          <a-option :value="1">巡检中</a-option>
          <a-option :value="2">已完成</a-option>
        </a-select>
      </div>
      <a-button type="primary" @click="createInspection">
        <template #icon><icon-plus /></template>
        新建巡检
      </a-button>
    </div>

    <!-- 巡检列表 -->
    <a-table
      :data="tableData"
      :loading="loading"
      :pagination="pagination"
      @page-change="onPageChange"
      @page-size-change="onPageSizeChange"
      stripe
    >
      <template #columns>
        <a-table-column title="巡检单号" data-index="code" />
        <a-table-column title="巡检名称" data-index="name" />
        <a-table-column title="巡检周期" data-index="cycle">
          <template #cell="{ record }">
            {{ cycleOptions.find(option => option.value === record.cycle)?.label }}
          </template>
        </a-table-column>
        <a-table-column title="巡检状态" data-index="status">
          <template #cell="{ record }">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusLabel(record.status) }}
            </a-tag>
          </template>
        </a-table-column>
        <a-table-column title="创建时间" data-index="createTime" />
        <a-table-column title="更新时间" data-index="updateTime" />
        <a-table-column title="操作" :width="detailColumnWidth" fixed="right">
          <template #cell="{ record }">
            <a-space>
              <a-button type="text" size="small" @click="viewDetail(record)">
                <template #icon><icon-eye /></template>
                详情
              </a-button>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>

    <!-- 添加新建巡检弹窗 -->
    <a-modal
      v-model:visible="createModalVisible"
      title="新建巡检"
      @ok="handleCreateOk"
      @cancel="handleCreateCancel"
      :ok-loading="createLoading"
    >
      <a-form
        ref="createFormRef"
        :model="createForm"
        :rules="createRules"
        label-align="right"
        :style="{ width: '600px' }"
      >
        <a-form-item field="name" label="巡检名称" :rules="createRules.name">
          <a-input v-model="createForm.name" placeholder="请输入巡检名称" />
        </a-form-item>
        
        <a-form-item field="cycle" label="巡检周期" :rules="createRules.cycle">
          <a-select v-model="createForm.cycle" placeholder="请选择巡检周期">
            <a-option 
              v-for="option in cycleOptions" 
              :key="option.value" 
              :value="option.value"
            >
              {{ option.label }}
            </a-option>
          </a-select>
        </a-form-item>
        
        <!-- 巡检项目列表 -->
        <div v-for="(item, index) in createForm.items" :key="index" class="mb-4">
          <div class="flex justify-between items-center mb-2">
            <h3 class="text-lg font-medium">巡检项目 {{ index + 1 }}</h3>
            <a-button
              v-if="index > 0"
              type="text"
              status="danger"
              @click="removeInspectionItem(index)"
            >
              删除
            </a-button>
          </div>
          
          <a-form-item
            :field="`items.${index}.name`"
            label="项目名称"
            :rules="createRules['items.*.name']"
          >
            <a-input v-model="item.name" placeholder="请输入项目名称" />
          </a-form-item>
          
          <a-form-item
            :field="`items.${index}.checkPoints`"
            label="检查点"
            :rules="createRules['items.*.checkPoints']"
          >
            <a-input-tag
              v-model="item.checkPoints"
              placeholder="请输入检查点，按回车确认"
            />
          </a-form-item>
          
          <a-form-item
            :field="`items.${index}.standardValue`"
            label="标准值"
            :rules="createRules['items.*.standardValue']"
          >
            <a-input v-model="item.standardValue" placeholder="请输入标准值" />
          </a-form-item>
          
          <a-form-item :field="`items.${index}.unit`" label="单位">
            <a-input v-model="item.unit" placeholder="请输入单位（选填）" />
          </a-form-item>
        </div>
        
        <!-- 添加巡检项目按钮 -->
        <div class="flex justify-center mt-4">
          <a-button type="dashed" @click="addInspectionItem">
            <template #icon><icon-plus /></template>
            添加巡检项目
          </a-button>
        </div>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import type { FormInstance } from '@arco-design/web-vue'
import { IconPlus, IconEye } from '@arco-design/web-vue/es/icon'
import type {
  InspectionPlan,
  InspectionPlanQuery,
  InspectionPlanCreateDTO,
  InspectionItem
} from '@/types/inspection'
import {
  getInspectionPlanList,
  createInspectionPlan
} from '@/services/inspection'

// 搜索参数
const searchParams = reactive({
  code: '',
  status: undefined as number | undefined
})

// 表格相关
const loading = ref(false)
const tableData = ref<InspectionPlan[]>([])
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: true,
  showJumper: true,
  showPageSize: true,
  pageSizeOptions: [10, 20, 50, 100]
})

const detailColumnWidth = 200

// 新建巡检相关
const createModalVisible = ref(false)
const createLoading = ref(false)
const createFormRef = ref<FormInstance>()
const createForm = reactive<InspectionPlanCreateDTO>({
  name: '',
  cycle: 1,
  managerId: 1, // 暂时写死
  items: [
    {
      name: '',
      checkPoints: [],
      standardValue: '',
      unit: ''
    }
  ]
})

// 巡检周期选项
const cycleOptions = [
  { value: 0, label: '每天' },
  { value: 1, label: '每周' },
  { value: 2, label: '每月' },
  { value: 3, label: '每季度' }
]

// 表单校验规则
const createRules = {
  name: [
    { required: true, message: '请输入巡检名称' },
    { maxLength: 50, message: '巡检名称最多50个字符' }
  ],
  cycle: [
    { required: true, message: '请选择巡检周期' }
  ],
  'items.*.name': [
    { required: true, message: '请输入巡检项目名称' }
  ],
  'items.*.checkPoints': [
    { required: true, message: '请输入检查点' }
  ],
  'items.*.standardValue': [
    { required: true, message: '请输入标准值' }
  ]
}

// 状态工具函数
const getStatusLabel = (status: number) => {
  const statusMap: Record<number, string> = {
    0: '待巡检',
    1: '巡检中',
    2: '已完成'
  }
  return statusMap[status] || '未知状态'
}

const getStatusColor = (status: number) => {
  const colorMap: Record<number, string> = {
    0: 'orange',
    1: 'blue',
    2: 'green'
  }
  return colorMap[status] || 'default'
}

// 获取巡检列表
const fetchInspectionList = async () => {
  loading.value = true
  try {
    const params: InspectionPlanQuery = {
      page: pagination.current,
      size: pagination.pageSize,
      status: searchParams.status
    }

    const res = await getInspectionPlanList(params)
    console.log('获取巡检列表响应:', res)
    
    const { data: response } = res
    if (response.code === 1) {
      tableData.value = response.data.records
      pagination.total = response.data.total
    } else {
      Message.error(response.msg || '获取列表失败')
    }
  } catch (error) {
    console.error('获取巡检列表失败:', error)
    Message.error('获取巡检列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchInspectionList()
}

// 分页
const onPageChange = (page: number) => {
  pagination.current = page
  fetchInspectionList()
}

const onPageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  fetchInspectionList()
}

// 新建巡检
const createInspection = () => {
  createModalVisible.value = true
  Object.assign(createForm, {
    name: '',
    cycle: 1,
    managerId: 1,
    items: [
      {
        name: '',
        checkPoints: [],
        standardValue: '',
        unit: ''
      }
    ]
  })
}

// 添加巡检项目
const addInspectionItem = () => {
  createForm.items.push({
    name: '',
    checkPoints: [],
    standardValue: '',
    unit: ''
  })
}

// 删除巡检项目
const removeInspectionItem = (index: number) => {
  createForm.items.splice(index, 1)
}

// 处理新建巡检
const handleCreateOk = async () => {
  try {
    await createFormRef.value?.validate()
    createLoading.value = true
    
    const res = await createInspectionPlan(createForm)
    console.log('创建巡检计划响应:', res)
    
    const { data: response } = res
    if (response.code === 1) {
      Message.success('创建成功')
      createModalVisible.value = false
      await fetchInspectionList()
    } else {
      Message.error(response.msg || '创建失败')
    }
  } catch (error) {
    console.error('创建巡检计划失败:', error)
    Message.error('创建失败')
  } finally {
    createLoading.value = false
  }
}

const handleCreateCancel = () => {
  createFormRef.value?.resetFields()
  createModalVisible.value = false
}

// 查看详情
const viewDetail = (record: InspectionPlan) => {
  Message.info(`查看巡检单 ${record.code} 的详细信息`)
}

onMounted(() => {
  fetchInspectionList()
})
</script>

<style scoped>
.arco-tag {
  padding: 4px 8px;
  font-size: 14px;
}

.arco-btn-text {
  padding: 4px 8px;
}

.arco-space {
  gap: 8px;
}
</style> 